<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Traits\ApiHelper;
use http\Exception\RuntimeException;
use Illuminate\Contracts\Cache\Lock;
use Illuminate\Support\Facades\Cache;
use JetBrains\PhpStorm\ArrayShape;

class BaseController extends \App\Http\Controllers\Api\BaseController
{
    use ApiHelper;

    protected string $authKey = 'Admin';

    /* @phpstan-ignore-next-line */
    #[ArrayShape(['controller' => "string", 'method' => "string"])] public function getControllerAndFunction(): array
    {
        $action = request()->route()?->getActionName();
        if (is_null($action)) {
            throw new RuntimeException("action不存在");
        }
        list($class, $method) = explode('@', $action);
        $class = substr((string)strrchr($class, '\\'), 1);
        return [
            'controller' => $class,
            'method' => $method
        ];
    }

    /**
     * 获得锁
     * @param string|int $flag
     * @param int $seconds
     * @return Lock
     */
    public function getLock(string|int $flag = '', int $seconds = 100): Lock
    {
        $routeInfo = $this->getControllerAndFunction();
        return Cache::lock($this->authKey . '.' . $routeInfo['controller'] . '.' . $routeInfo['method'] . $flag, 100);
    }
}
